package com.laber.controller;

import com.laber.domain.User;
import com.laber.properties.JwtProperties;
import com.laber.utils.MyJwtUtil;
import com.laber.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.checkerframework.checker.units.qual.A;
import org.hibernate.validator.constraints.URL;
import com.laber.domain.Result;
import com.laber.service.UserService;
import com.laber.utils.JwtUtil;
import com.laber.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated  // => Spring Validation
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JwtProperties jwtProperties;


    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,
                           @Pattern(regexp = "^\\S{5,16}$") String password) {
        //查询用户
        User user = userService.findByUerName(username);
        if (user == null) {
            //注册
            userService.register(username, password);
            return Result.success("注册成功");
        } else {
            return Result.error("用户名已被占用");
        }
    }

    //结果需要返回token，是一个字符串
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,
                                @Pattern(regexp = "^\\S{5,16}$") String password) {
        //根据用户名查询用户
        User loginuser = userService.findByUerName(username);
        System.out.println("登录用户：" + loginuser);
        //判断用户是否存在
        if (loginuser == null) {
            return Result.error("用户名不存在");
        }
        //判断密码是否正确 loginUser对象中的password是密文
        if (Md5Util.getMD5String(password).equals(loginuser.getPassword())) {
            //登录成功
            Map<String, Object> clamis = new HashMap<>();
            clamis.put("id", loginuser.getId());
            clamis.put("username", loginuser.getUsername());
//            String token = JwtUtil.genToken(clamis);
            String token = MyJwtUtil.createToken(jwtProperties.getSecret(), jwtProperties.getExpireTime(), clamis);
            //把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);

            return Result.success("登录成功", token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> getUserInfo() {
//        Map<String, Object> clamis = JwtUtil.parseToken(token);
//        String username = (String) clamis.get("username");
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUerName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    //@PatchMapping 注解与其他请求方式的区别：HTTP PATCH 方法通常用于更新资源的部分内容
    @PatchMapping("/updateAvatar") //Avatar =>头像
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        //1.校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String repwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) ||
                !StringUtils.hasLength(newPwd) ||
                !StringUtils.hasLength(repwd)) {
            return Result.error("缺少必要的参数");
        }
        //原密码是否正确
        //地哦用userService根据用户名拿到原密码，在和old_pwd对比
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUerName(username);

        if (!user.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码填写不正确");
        }
        //newPwd和rePwd是否一样
        if (!repwd.equals(newPwd)) {
            return Result.error("两次填写的新密码一致");
        }
        //2.调用service完成密码更新
        userService.updatePwd(newPwd);
        //删除原redis中的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
